<template>
  <div class="statistics-container">
    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="统计维度">
          <el-select
            v-model="filterForm.dimension"
            style="width: 150px"
            @change="handleDimensionChange"
          >
            <el-option label="按日统计" value="day" />
            <el-option label="按周统计" value="week" />
            <el-option label="按月统计" value="month" />
            <el-option label="按年统计" value="year" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            @change="handleDateChange"
          />
        </el-form-item>

        <el-form-item label="订单状态">
          <el-select
            v-model="filterForm.status"
            multiple
            placeholder="选择状态"
            style="width: 200px"
          >
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品类型">
          <el-select
            v-model="filterForm.productType"
            multiple
            placeholder="选择类型"
            style="width: 200px"
          >
            <el-option label="活动报名" value="activity" />
            <el-option label="会员费" value="membership" />
            <el-option label="培训课程" value="training" />
            <el-option label="比赛报名" value="match" />
            <el-option label="器材购买" value="equipment" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出报表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-card class="overview-card" shadow="never">
      <template #header>
        <span class="card-title">数据概览</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon order-icon">
              <IconifyIconOffline icon="ep:document" />
            </div>
            <div class="stat-content">
              <div class="stat-value">
                {{ overview.totalOrders.toLocaleString() }}
              </div>
              <div class="stat-label">总订单数</div>
              <div
                class="stat-trend"
                :class="overview.orderTrend >= 0 ? 'positive' : 'negative'"
              >
                <IconifyIconOffline
                  :icon="
                    overview.orderTrend >= 0 ? 'ep:arrow-up' : 'ep:arrow-down'
                  "
                />
                {{ Math.abs(overview.orderTrend) }}%
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon amount-icon">
              <IconifyIconOffline icon="ep:money" />
            </div>
            <div class="stat-content">
              <div class="stat-value">
                ¥{{ overview.totalAmount.toLocaleString() }}
              </div>
              <div class="stat-label">总交易金额</div>
              <div
                class="stat-trend"
                :class="overview.amountTrend >= 0 ? 'positive' : 'negative'"
              >
                <IconifyIconOffline
                  :icon="
                    overview.amountTrend >= 0 ? 'ep:arrow-up' : 'ep:arrow-down'
                  "
                />
                {{ Math.abs(overview.amountTrend) }}%
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon success-icon">
              <IconifyIconOffline icon="ep:check" />
            </div>
            <div class="stat-content">
              <div class="stat-value">
                {{ overview.successOrders.toLocaleString() }}
              </div>
              <div class="stat-label">成功订单</div>
              <div
                class="stat-trend"
                :class="overview.successTrend >= 0 ? 'positive' : 'negative'"
              >
                <IconifyIconOffline
                  :icon="
                    overview.successTrend >= 0 ? 'ep:arrow-up' : 'ep:arrow-down'
                  "
                />
                {{ Math.abs(overview.successTrend) }}%
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon rate-icon">
              <IconifyIconOffline icon="ep:data-analysis" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overview.successRate }}%</div>
              <div class="stat-label">成功率</div>
              <div
                class="stat-trend"
                :class="overview.rateTrend >= 0 ? 'positive' : 'negative'"
              >
                <IconifyIconOffline
                  :icon="
                    overview.rateTrend >= 0 ? 'ep:arrow-up' : 'ep:arrow-down'
                  "
                />
                {{ Math.abs(overview.rateTrend) }}%
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 订单趋势图 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="chart-header">
              <span class="card-title">订单趋势</span>
              <el-radio-group
                v-model="trendType"
                size="small"
                @change="updateTrendChart"
              >
                <el-radio-button value="count">订单数</el-radio-button>
                <el-radio-button value="amount">金额</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <div ref="trendChartRef" style="width: 100%; height: 300px" />
        </el-card>
      </el-col>

      <!-- 订单状态分布 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span class="card-title">订单状态分布</span>
          </template>

          <div ref="statusChartRef" style="width: 100%; height: 300px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 商品类型分析 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span class="card-title">商品类型分析</span>
          </template>

          <div ref="productChartRef" style="width: 100%; height: 300px" />
        </el-card>
      </el-col>

      <!-- 支付方式统计 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span class="card-title">支付方式统计</span>
          </template>

          <div ref="paymentChartRef" style="width: 100%; height: 300px" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <span class="card-title">详细数据</span>
      </template>

      <el-table v-loading="loading" :data="detailData" stripe border>
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="totalOrders" label="总订单数" width="100" />
        <el-table-column prop="successOrders" label="成功订单" width="100" />
        <el-table-column prop="cancelledOrders" label="取消订单" width="100" />
        <el-table-column prop="refundedOrders" label="退款订单" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="successAmount" label="成功金额" width="120">
          <template #default="{ row }">
            ¥{{ row.successAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="refundAmount" label="退款金额" width="120">
          <template #default="{ row }">
            ¥{{ row.refundAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="successRate" label="成功率" width="100">
          <template #default="{ row }"> {{ row.successRate }}% </template>
        </el-table-column>
        <el-table-column prop="avgAmount" label="平均订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.avgAmount.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import * as echarts from "echarts";
import dayjs from "dayjs";

// 状态
const loading = ref(false);
const trendType = ref("count");
const trendChartRef = ref();
const statusChartRef = ref();
const productChartRef = ref();
const paymentChartRef = ref();

// 筛选表单
const filterForm = reactive({
  dimension: "day",
  dateRange: [
    dayjs().subtract(30, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD")
  ],
  status: [],
  productType: []
});

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 概览数据
const overview = reactive({
  totalOrders: 1256,
  totalAmount: 125680.5,
  successOrders: 1142,
  successRate: 90.9,
  orderTrend: 12.5,
  amountTrend: 18.3,
  successTrend: 8.7,
  rateTrend: -2.1
});

// 详细数据
const detailData = ref([
  {
    date: "2024-01-15",
    totalOrders: 45,
    successOrders: 42,
    cancelledOrders: 2,
    refundedOrders: 1,
    totalAmount: 4580.0,
    successAmount: 4280.0,
    refundAmount: 50.0,
    successRate: 93.3,
    avgAmount: 101.78
  },
  {
    date: "2024-01-14",
    totalOrders: 38,
    successOrders: 35,
    cancelledOrders: 3,
    refundedOrders: 0,
    totalAmount: 3920.0,
    successAmount: 3620.0,
    refundAmount: 0.0,
    successRate: 92.1,
    avgAmount: 103.16
  }
]);

// 趋势数据
const trendData = {
  count: {
    dates: ["01-10", "01-11", "01-12", "01-13", "01-14", "01-15", "01-16"],
    values: [32, 28, 35, 42, 38, 45, 41]
  },
  amount: {
    dates: ["01-10", "01-11", "01-12", "01-13", "01-14", "01-15", "01-16"],
    values: [3200, 2890, 3650, 4280, 3920, 4580, 4150]
  }
};

// 状态分布数据
const statusData = [
  { name: "已支付", value: 1142, color: "#67C23A" },
  { name: "待支付", value: 68, color: "#E6A23C" },
  { name: "已取消", value: 32, color: "#909399" },
  { name: "已退款", value: 14, color: "#F56C6C" }
];

// 商品类型数据
const productData = [
  { name: "活动报名", value: 456, amount: 45600 },
  { name: "培训课程", value: 324, amount: 64800 },
  { name: "会员费", value: 268, amount: 26800 },
  { name: "比赛报名", value: 156, amount: 15600 },
  { name: "器材购买", value: 52, amount: 10400 }
];

// 支付方式数据
const paymentData = [
  { name: "微信支付", value: 658, percentage: 57.6 },
  { name: "支付宝", value: 342, percentage: 29.9 },
  { name: "银行卡", value: 98, percentage: 8.6 },
  { name: "余额支付", value: 44, percentage: 3.9 }
];

// 维度变化
const handleDimensionChange = () => {
  // 根据维度调整日期范围
  const now = dayjs();
  switch (filterForm.dimension) {
    case "day":
      filterForm.dateRange = [
        now.subtract(30, "day").format("YYYY-MM-DD"),
        now.format("YYYY-MM-DD")
      ];
      break;
    case "week":
      filterForm.dateRange = [
        now.subtract(12, "week").format("YYYY-MM-DD"),
        now.format("YYYY-MM-DD")
      ];
      break;
    case "month":
      filterForm.dateRange = [
        now.subtract(12, "month").format("YYYY-MM-DD"),
        now.format("YYYY-MM-DD")
      ];
      break;
    case "year":
      filterForm.dateRange = [
        now.subtract(5, "year").format("YYYY-MM-DD"),
        now.format("YYYY-MM-DD")
      ];
      break;
  }
};

// 日期变化
const handleDateChange = () => {
  handleQuery();
};

// 查询
const handleQuery = () => {
  loadStatistics();
  updateAllCharts();
};

// 重置
const handleReset = () => {
  filterForm.dimension = "day";
  filterForm.dateRange = [
    dayjs().subtract(30, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD")
  ];
  filterForm.status = [];
  filterForm.productType = [];
  handleQuery();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中");
};

// 更新趋势图
const updateTrendChart = () => {
  if (!trendChartRef.value) return;

  const chart = echarts.init(trendChartRef.value);
  const data = trendData[trendType.value];

  const option = {
    title: {
      text: trendType.value === "count" ? "订单数趋势" : "订单金额趋势",
      left: "center",
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        const value = params[0].value;
        const unit = trendType.value === "count" ? "单" : "元";
        return `${params[0].name}<br/>${params[0].seriesName}: ${value}${unit}`;
      }
    },
    xAxis: {
      type: "category",
      data: data.dates,
      axisLabel: { fontSize: 12 }
    },
    yAxis: {
      type: "value",
      axisLabel: { fontSize: 12 }
    },
    series: [
      {
        name: trendType.value === "count" ? "订单数" : "订单金额",
        type: "line",
        data: data.values,
        smooth: true,
        itemStyle: { color: "#409EFF" },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.1)" }
            ]
          }
        }
      }
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    }
  };

  chart.setOption(option);
};

// 更新状态分布图
const updateStatusChart = () => {
  if (!statusChartRef.value) return;

  const chart = echarts.init(statusChartRef.value);

  const option = {
    title: {
      text: "订单状态分布",
      left: "center",
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      left: "left",
      textStyle: { fontSize: 12 }
    },
    series: [
      {
        name: "订单状态",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["60%", "50%"],
        data: statusData.map(item => ({
          name: item.name,
          value: item.value,
          itemStyle: { color: item.color }
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        label: {
          show: true,
          formatter: "{b}: {c}"
        }
      }
    ]
  };

  chart.setOption(option);
};

// 更新商品类型图
const updateProductChart = () => {
  if (!productChartRef.value) return;

  const chart = echarts.init(productChartRef.value);

  const option = {
    title: {
      text: "商品类型分析",
      left: "center",
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    legend: {
      data: ["订单数", "金额"],
      top: "bottom"
    },
    xAxis: {
      type: "category",
      data: productData.map(item => item.name),
      axisLabel: { fontSize: 12 }
    },
    yAxis: [
      {
        type: "value",
        name: "订单数",
        position: "left",
        axisLabel: { fontSize: 12 }
      },
      {
        type: "value",
        name: "金额",
        position: "right",
        axisLabel: { fontSize: 12 }
      }
    ],
    series: [
      {
        name: "订单数",
        type: "bar",
        data: productData.map(item => item.value),
        itemStyle: { color: "#409EFF" }
      },
      {
        name: "金额",
        type: "line",
        yAxisIndex: 1,
        data: productData.map(item => item.amount),
        itemStyle: { color: "#67C23A" }
      }
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true
    }
  };

  chart.setOption(option);
};

// 更新支付方式图
const updatePaymentChart = () => {
  if (!paymentChartRef.value) return;

  const chart = echarts.init(paymentChartRef.value);

  const option = {
    title: {
      text: "支付方式统计",
      left: "center",
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    xAxis: {
      type: "category",
      data: paymentData.map(item => item.name),
      axisLabel: { fontSize: 12 }
    },
    yAxis: {
      type: "value",
      axisLabel: { fontSize: 12 }
    },
    series: [
      {
        name: "订单数",
        type: "bar",
        data: paymentData.map(item => item.value),
        itemStyle: {
          color: (params: any) => {
            const colors = ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C"];
            return colors[params.dataIndex % colors.length];
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: (params: any) => {
            const percentage = paymentData[params.dataIndex].percentage;
            return `${params.value} (${percentage}%)`;
          }
        }
      }
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    }
  };

  chart.setOption(option);
};

// 更新所有图表
const updateAllCharts = () => {
  nextTick(() => {
    updateTrendChart();
    updateStatusChart();
    updateProductChart();
    updatePaymentChart();
  });
};

// 分页变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadStatistics();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadStatistics();
};

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    pagination.total = 30;
  } catch (error) {
    ElMessage.error("加载统计数据失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadStatistics();
  updateAllCharts();
});
</script>

<style scoped lang="scss">
.statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-card,
.overview-card,
.table-card {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
    margin-right: 16px;

    &.order-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.amount-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.success-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.rate-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 14px;
      color: #606266;
      margin-bottom: 4px;
    }

    .stat-trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 2px;

      &.positive {
        color: #67c23a;
      }

      &.negative {
        color: #f56c6c;
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .statistics-container {
    padding: 10px;
  }

  .stat-item {
    flex-direction: column;
    text-align: center;

    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }

  .chart-card {
    height: 350px;
  }

  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>
